package ua.amsoft.brelok.loader;

import ua.amsoft.brelok.dao.DepartamentUsageReportsDAO;
import ua.amsoft.brelok.dao.IDepartamentUsageReportsDAO;
import ua.amsoft.brelok.dto.DepartamentUsageResultReports;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;

public class DepartamentUsageReportsTaskLoader extends
        AsyncTaskLoader<DepartamentUsageResultReports> {
    
    private DepartamentUsageResultReports reports;
    
    private final IDepartamentUsageReportsDAO dao;
    
    /**
     * @param context - {@link Context}
     */
    public DepartamentUsageReportsTaskLoader(final Context context) {
        super(context);
        this.dao = new DepartamentUsageReportsDAO(context);
    }
    
    @Override
    public DepartamentUsageResultReports loadInBackground() {
        final DepartamentUsageResultReports data = this.dao.get();
        return data;
    }
    
    @Override
    public void deliverResult(final DepartamentUsageResultReports data) {
        this.reports = data;
        if (isStarted()) {
            super.deliverResult(data);
        }
    }
    
    @Override
    protected void onStartLoading() {
        if (this.reports != null) {
            this.deliverResult(this.reports);
        }
        if (takeContentChanged() || (this.reports == null)) {
            forceLoad();
        }
    }
    
    @Override
    protected void onStopLoading() {
        cancelLoad();
    }
    
    @Override
    protected void onReset() {
        super.onReset();
        this.onStopLoading();
    }
}
